//购物车的store

import { defineStore } from "pinia";
import { ref, computed } from "vue";
import type { Goods } from "@/model"; //引入自定义数据类型

export const useCart = defineStore(
  "cart",
  () => {
    //定义状态数据(state) - 购物车中存储的所有商品
    const cartList = ref<Goods[]>([]);

    //商品总价
    const totalPrice = computed(() => {
      var total = 0;
      for (var v of cartList.value) {
        total += v.price * v.discount * v.num;
      }
      return total.toFixed(2);
    });

    //添加新商品的方法(action)
    const addCart = (goods: Goods) => {
      //查找是否购买过该商品
      const item = cartList.value.find((v) => v.id == goods.id);
      if (item) {
        //重复购买，数量累加
        item.num += goods.num;
      } else {
        //添加新商品
        cartList.value.push(goods);
      }
    };

    //删除单个商品
    const delGoods = (id: number) => {
      cartList.value.forEach((v, k) => {
        if (v.id == id) {
          cartList.value.splice(k, 1);
        }
      });
    };

    //清空购物车
    const clearCart = () => {
      cartList.value.splice(0, cartList.value.length);
    };

    //订单成功，删除已购买商品
    const delPayGoods = (selectGoods: Goods[]) => {
      selectGoods.forEach((v) => {
        for (var i = 0; i < cartList.value.length; i++) {
          if (v.id === cartList.value[i]!.id) {
            cartList.value.splice(i, 1);
            break;
          }
        }
      });
    };

    //以对象形式返回
    return { cartList, totalPrice, addCart, delGoods, clearCart, delPayGoods };
  },
  {
    persist: {
      key: "cart",
      storage: localStorage,
      pick: ["cartList"],
    },
  }
);
